import 'dart:async';
import 'dart:typed_data';

import 'package:bluetooth_protocols_parser_plugin/src/huari/response/huari_response_data.dart';
import 'package:bluetooth_protocols_plugin/library.dart';
import 'package:flutter/material.dart';

import '../cmd/car_key_cmd.dart';
import '../huari_protocol.dart';

class CarKeyProtocol extends HuariProtocol {
  @override
  HuariPrivateIntructionMessage get privateInstrMessage =>
      _CarKeyPrivateIntructionMessage();

  //
  // 蓝牙主动响应监听
  StreamSubscription? _bluetoothNotifyStreamSubscription;

  @override
  void cancelBluetoothNotifyStream() {
    _bluetoothNotifyStreamSubscription?.cancel();
    _bluetoothNotifyStreamSubscription = null;
  }

  @override
  void listenBluetoothNotifyStream(
      {Function(HuariResponseData p1)? callbackNfcCardPairSuccess,
      Function(HuariRealtimeInfo p1)? callbackRealtimeInfo,
      Function(HuariIntegratedRealtimeInfo p1)? callbackRealtimeAllInfo}) {
    // 先取消已有订阅
    _bluetoothNotifyStreamSubscription?.cancel();
    _bluetoothNotifyStreamSubscription = responseNotifyStream?.listen((p0) {
      // 处理主动响应数据，根据实际协议解析
      if (p0.isEmpty) return;
      HuariMessage msg = HuariMessage.fromList(Uint8List.fromList(p0));
      if (msg.data == null) return;
      switch (msg.msgIdentify()) {
        case '${0x8E}': // 0x8E表示NFC卡配卡结果
          if (msg.data != null && msg.data!.toBytes() != null) {
            HuariResponseData rsp =
                HuariResponseData(rsp: msg.data!.toBytes()!);
            debugPrint('NFC卡配对${rsp.isSuccess ? '成功' : '失败'}');
            if (callbackNfcCardPairSuccess != null) {
              callbackNfcCardPairSuccess(rsp);
            }
          }
          break;
        case '${0xFD}': // 0xFD表示实时信息
          Uint8List? data = msg.data?.toBytes();
          // 处理实时信息
          if (data == null || data.isEmpty) {
            debugPrint('实时信息数据为空');
            return;
          }
          if (callbackRealtimeInfo != null) {
            callbackRealtimeInfo(HuariRealtimeInfo.fromBytes(data));
          }
          break;
        default:
          // 其他消息类型
          break;
      }
    });
  }
}

class _CarKeyPrivateIntructionMessage extends HuariPrivateIntructionMessage {
  @override
  get privateRequestBody => _CarKeyPrivateRequestBody();
}

class _CarKeyPrivateRequestBody extends HuariPrivateRequestBody {
  @override
  HuariCmdBase get cmdBase => CarKeyCmd();
}
